package com.whmskj.xjlhbc.mobile.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.Bcry11ygsqbd;
import com.whmskj.xjlhbc.domain.PersonnelManagementDataSheets;
import com.whmskj.xjlhbc.domain.StatisticalTableShowingTheNumber;
import com.whmskj.xjlhbc.mapper.Bcry11ygsqbdMapper;
import com.whmskj.xjlhbc.mapper.StatisticalTableShowingTheNumberMapper;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Tag(name = "岗位定员",description = "岗位定员")
@RequestMapping("/gwdy")
public class GwdyController {

    @Autowired
    private StatisticalTableShowingTheNumberMapper mapper;

    @Autowired
    private Bcry11ygsqbdMapper bcry11ygsqbdMapper;

    @Autowired
    private IPersonnelManagementDataSheetsService personnelManagementDataSheetsService;

    /**
     * 岗位定员
     */
    @GetMapping("/list")
    @Operation(description = "岗位定员")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult list(String sector,String position){
        LambdaQueryWrapper<StatisticalTableShowingTheNumber> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(sector), StatisticalTableShowingTheNumber::getSector, sector);
        wrapper.eq(StringUtils.hasText(position), StatisticalTableShowingTheNumber::getPositions, position);
        List<StatisticalTableShowingTheNumber> list = mapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    private static final String staus1 = "待审核";
    private static final String staus2 = "已审核";
    private static final String staus3 = "已退回";
    private static final String ty = "同意";
    private static final String th = "退回";

    private static final String chief = "陶峰";

    /**
     * 用工申请历史记录
     */
    @GetMapping("/ygHistoryList")
    @Operation(description = "岗位定员")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult ygHistoryList(@RequestParam(defaultValue = "1") int type){
        Page.startPage();
        PersonnelManagementDataSheets personnel = getPersonnel();
        String sqr = personnel.getFe1e();
        LambdaQueryWrapper<Bcry11ygsqbd> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Bcry11ygsqbd::getYgsqtime);
        wrapper.eq(Bcry11ygsqbd::getYgsqr, sqr);
        if(type == 1){
            wrapper.eq(Bcry11ygsqbd::getAuditStatus, staus1);
        }
        if(type == 2){
            wrapper.eq(Bcry11ygsqbd::getAuditStatus, staus2);
        }
        if(type == 3){
            wrapper.eq(Bcry11ygsqbd::getAuditStatus, staus3);
        }
        List<Bcry11ygsqbd> list = bcry11ygsqbdMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }

    /**
     * 用工审核
     */
    @GetMapping("/ygAuditHistoryList")
    @Operation(description = "用工审核")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult ygAuditHistoryList(@RequestParam(defaultValue = "1") int type){
        Page.startPage();
        PersonnelManagementDataSheets personnel = getPersonnel();
        String name = personnel.getFe1e();
        boolean isChief = chief.equals(name);//是否厂长
        LambdaQueryWrapper<Bcry11ygsqbd> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Bcry11ygsqbd::getYgsqtime);
        if(isChief){
            wrapper.eq(Bcry11ygsqbd::getChief, name);
            if(type == 1){//待审核
                wrapper.eq(Bcry11ygsqbd::getLeadshzt, staus2);
                wrapper.eq(Bcry11ygsqbd::getChiefshzt, staus1);
            }
            if(type == 2){//已审核
                wrapper.eq(Bcry11ygsqbd::getChiefshzt, staus2);
            }
        }else{
            wrapper.eq(Bcry11ygsqbd::getHeadsbm, name);
            if(type == 1){//待审核
                wrapper.eq(Bcry11ygsqbd::getLeadshzt, staus1);
            }
            if(type == 2){//已审核
                wrapper.eq(Bcry11ygsqbd::getLeadshzt, staus2);

            }
        }
        List<Bcry11ygsqbd> list = bcry11ygsqbdMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }

    /**
     * 用工申请审核
     */
    @PostMapping("/ygAudit")
    @Operation(description = "用工申请审核")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult ygAudit(@RequestBody Bcry11ygsqbd body){
        String leadshzt = body.getLeadshzt();
        PersonnelManagementDataSheets personnel = getPersonnel();
        String name = personnel.getFe1e();
        boolean isChief = chief.equals(name);//是否厂长
        Long id = body.getId();
        Bcry11ygsqbd bcry11ygsqbd = bcry11ygsqbdMapper.selectById(id);
        if(ty.equals(leadshzt)){
            if(isChief){
                bcry11ygsqbd.setChiefshzt(staus2);
                bcry11ygsqbd.setChiefshyj(body.getLeadshyj());
                bcry11ygsqbd.setChieftime(DateUtil.now());
                bcry11ygsqbd.setAuditStatus(staus2);
            }else{
                bcry11ygsqbd.setLeadshzt(staus2);
                bcry11ygsqbd.setLeadshyj(body.getLeadshyj());
                bcry11ygsqbd.setLeadAuditTime(DateUtil.now());
            }
        }
        if(th.equals(leadshzt)){
            if(isChief){
                bcry11ygsqbd.setChiefshzt(staus3);
                bcry11ygsqbd.setChiefshyj(body.getLeadshyj());
                bcry11ygsqbd.setChieftime(DateUtil.now());
                bcry11ygsqbd.setAuditStatus(staus3);
            }else{
                bcry11ygsqbd.setLeadshzt(staus3);
                bcry11ygsqbd.setLeadshyj(body.getLeadshyj());
                bcry11ygsqbd.setLeadAuditTime(DateUtil.now());
                bcry11ygsqbd.setAuditStatus(staus3);
            }
        }
        int result = bcry11ygsqbdMapper.updateById(bcry11ygsqbd);
        return AjaxResult.success(result>0);
    }

    /**
     * 用工审核信息
     */
    @GetMapping("/ygShr")
    @Operation(description = "用工审核信息")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult ygShr(){
        PersonnelManagementDataSheets personnel = getPersonnel();
        String sector = personnel.getSector();
        String headsbm = bcry11ygsqbdMapper.selectDepartmentZg(sector);
        Map<String, String> map = new HashMap<>();
        map.put("headsbm", headsbm);
        map.put("chief", chief);
        return AjaxResult.success(map);
    }


    /**
     * 用工申请详情
     */
    @GetMapping("/ygDetailById")
    @Operation(description = "用工申请详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult ygDetailById(Long id){
        Bcry11ygsqbd bcry11ygsqbd = bcry11ygsqbdMapper.selectById(id);
        String chief = bcry11ygsqbd.getChief();
        String headsbm = bcry11ygsqbd.getHeadsbm();
        String ygsqr = bcry11ygsqbd.getYgsqr();
        LambdaQueryWrapper<PersonnelManagementDataSheets> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PersonnelManagementDataSheets::getFe1e, chief, headsbm,ygsqr);
        List<PersonnelManagementDataSheets> personnelManagementDataSheetsList = personnelManagementDataSheetsService.list(wrapper);
        PersonnelManagementDataSheets p = personnelManagementDataSheetsList.stream().filter(f -> f.getFe1e().equals(ygsqr))
                .findFirst().orElseGet(PersonnelManagementDataSheets::new);
        PersonnelManagementDataSheets p1 = personnelManagementDataSheetsList.stream().filter(f -> f.getFe1e().equals(headsbm))
                .findFirst().orElseGet(PersonnelManagementDataSheets::new);
        PersonnelManagementDataSheets p2 = personnelManagementDataSheetsList.stream().filter(f -> f.getFe1e().equals(chief))
                .findFirst().orElseGet(PersonnelManagementDataSheets::new);
        Map<String, Object> result = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("name", ygsqr);
        map.put("date", bcry11ygsqbd.getYgsqtime());
        map.put("position", p.getPositions1());
        map.put("auditStatus", "提交申请");
        map.put("yj", "");
        list.add(map);
        map = new HashMap<>();
        map.put("name", headsbm);
        map.put("date", bcry11ygsqbd.getLeadAuditTime());
        map.put("position", p1.getPositions1());
        map.put("auditStatus", bcry11ygsqbd.getLeadshzt());
        map.put("yj", bcry11ygsqbd.getLeadshyj());
        list.add(map);
        map = new HashMap<>();
        map.put("name", chief);
        map.put("date", bcry11ygsqbd.getChieftime());
        map.put("position", p2.getPositions1());
        map.put("auditStatus", bcry11ygsqbd.getChiefshzt());
        map.put("yj", bcry11ygsqbd.getChiefshyj());
        list.add(map);
        result.put("ygDetail", bcry11ygsqbd);
        result.put("auditList", list);
        return AjaxResult.success(result);
    }

    /**
     * 提交/编辑用工申请
     */
    @PostMapping("/saveUpdateYg")
    @Operation(description = "用工申请提交")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult saveUpdateYg(@RequestBody Bcry11ygsqbd body){
        PersonnelManagementDataSheets personnel = getPersonnel();
        String sector = personnel.getSector();
        Long id = body.getId();
        if(Objects.isNull(id)) {
            body.setYgsqdate(DateUtil.today());
            body.setYgsqtime(DateUtil.now());
            body.setYgsqr(personnel.getFe1e());
            body.setYgsqbu(sector);
            body.setChief(chief);
            body.setAuditStatus(staus1);
            body.setLeadshzt(staus1);
            body.setChiefshzt(staus1);
            body.setSqdbh(getSqdbh());
            String headsbm = bcry11ygsqbdMapper.selectDepartmentZg(sector);
            body.setHeadsbm(headsbm);
        }
        int result = Objects.nonNull(id) ? bcry11ygsqbdMapper.updateById(body) : bcry11ygsqbdMapper.insert(body);
        return AjaxResult.success(result>0);
    }

    private String getSqdbh(){
        String start = DateUtil.beginOfMonth(DateUtil.date()).toDateStr();
        LambdaQueryWrapper<Bcry11ygsqbd> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(Bcry11ygsqbd::getYgsqdate, start,DateUtil.today())
                .notLike(Bcry11ygsqbd::getSqdbh,"P")
                .orderByDesc(Bcry11ygsqbd::getSqdbh).last("limit 1");
        String yyMMdd = DateUtil.format(DateUtil.date(), "yyMM");
        String str = StrUtil.padPre(String.valueOf(0), 3, "0");
        Bcry11ygsqbd defaultOne =new Bcry11ygsqbd();
        defaultOne.setSqdbh(yyMMdd+str);
        Bcry11ygsqbd bcry11ygsqbd = Optional.ofNullable(bcry11ygsqbdMapper.selectOne(wrapper)).orElse(defaultOne);
        long val = NumberUtil.parseLong(bcry11ygsqbd.getSqdbh()) + 1;
        return String.valueOf(val);
    }

    /**
     * 删除用工申请
     */
    @PostMapping("/deleteYg/{id}")
    @Operation(description = "用工申请删除")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult deleteYg(@PathVariable Long id){
        int result = bcry11ygsqbdMapper.deleteById(id);
        return AjaxResult.success(result>0);
    }

    private PersonnelManagementDataSheets getPersonnel(){
        return personnelManagementDataSheetsService.getByLoginUserId();
    }
}
